/* 
 * File:	main.c
 * Authors: Johan Dahlberg <S102591>
 *				Daniel Jansson <S102496>
 * ---------------------------------
 * Task 4b: This program solves a maze by recursive backtracking.
 */
#include <stdio.h>
#include "genlib.h"
#include "mazelib.h"
#include "simpio.h"

/*
 * Constants
 * ---------
 * MazeFile -- Name of the file containing the maze
 */
//#define MazeFile "C:\\unmark.maz"

/* Prototypes */
static bool SolveMaze(pointT pt);
static bool useUnmarking = TRUE;
static pointT AdjacentPoint(pointT pt, directionT dir);
static void clearMarks(void);
static int nRecursiveCalls = 0;

/* Code */
main() {
	int shortestPath;

	string MazeFile;
	
	printf("Please input the file you want to read from\n");
	MazeFile = GetLine();
	
	ReadMazeMap(MazeFile);
    
   SolveMaze(GetStartPosition());
	printf("Number of recursiveCalls: %d\n",nRecursiveCalls);
	
	nRecursiveCalls = 0;
	
	useUnmarking = FALSE;
	ReadMazeMap(MazeFile);
	SolveMaze(GetStartPosition());
	printf("Number of recursiveCalls without marking: %d\n",nRecursiveCalls);
	//clearMarks();
	getchar();
}

static void clearMarks(pointT pt){
	//printf("%d %d\n",mazeWidth,mazeHeight);
	int x,y = 0;
		/*
	for(x = 0;x <= mazeWidth; x++){
		maze[pt.x][pt.y].marked = FALSE;
	}
	*/

	//maze[pt.x][pt.y].marked = TRUE;
}

/*
 * Function: SolveMaze
 * Usage: if (SolveMaze(pt)) . . .
 * -------------------------------
 * This function attempts to generate a solution to the current
 * maze from point pt.  SolveMaze returns TRUE if the maze has
 * a solution and FALSE otherwise.  The implementation uses
 * recursion to solve the submazes that result from marking the
 * current square and moving one step along each open passage.
 */
static bool SolveMaze(pointT pt) {
	directionT dir;
	nRecursiveCalls++;
   
	if (OutsideMaze(pt)){
		return (TRUE);
	}
   
	if (IsMarked(pt)) {
		return (FALSE);
	}
   
	MarkSquare(pt);
   for (dir = North; dir <= West; dir++) {
		if (!WallExists(pt, dir)) {
			if (SolveMaze(AdjacentPoint(pt, dir))) {
				return (TRUE);
         }
      }
   }
	
	if(useUnmarking) {
		UnmarkSquare(pt);
	}
	
	return (FALSE);
}

/*
 * Function: AdjacentPoint
 * Usage: newpt = AdjacentPoint(pt, dir);
 * --------------------------------------
 * This function returns the pointT that results from moving
 * one square from pt in the direction specified by dir.  For
 * example, if pt is the point (1,1), AdjacentPoint(pt, East)
 * would return the point (2,1).
 */
static pointT AdjacentPoint(pointT pt, directionT dir) {
    pointT newpt;

    newpt = pt;
    switch (dir) {
      case North: newpt.y++; break;
      case East:  newpt.x++; break;
      case South: newpt.y--; break;
      case West:  newpt.x--; break;;
    }

    return newpt;
}